import axios from 'axios'
import {jsonToFormData, isEmptyObject} from '../common/vue-expand-func'
import {profile} from "../config/base";
import jsonp from 'jsonp'
import iView from 'iview'
import router from '../router/index'
import {CLEAR_LOGIN_DATA} from "../store/param/mutation_type";

let ReqContentType = {
  APPLICATION_JSON: 'application/json;charset=UTF-8',
  APPLICATION_FORM: 'application/x-www-form-urlencoded;charset=UTF-8'
}
let Method = {
  GET: 'GET',
  POST: 'POST'
}

let BASE_URL = profile.apiHost

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'//设置该请求头用于服务器判断是否Ajax请求

/**
 * 请求前配置
 */
axios.interceptors.request.use((config) => { //请求操作
  let token = localStorage.getItem('token')
  if (!isEmptyObject(token))
    config.headers['Authorization'] = token
  if (config.method === 'post') {
    if (config.data instanceof Object) { //如果传进来的是一个对象
      let params = ''
      for (let k in config.data) {
        params += `&${k}=${config.data[k]}`
      }
      config.data = params
    }
  }
  return config
}, (error) => {
  console.log('错误的传参', 'fail')
  return Promise.reject(error)
})

/**
 * 响应配置
 */
axios.interceptors.response.use((response) => {
  if (response.data) {
    return response.data
  }
  return response
}, (error) => {
  switch (error.response.status) {
    case 401:
      /** 无权限访问，去登录 **/
      let store = require('../store/main').default
      store.commit(CLEAR_LOGIN_DATA)
      iView.Modal.warning({
        title: '登录信息过期',
        content: '<p>登录信息已过期，请重新登录</p>',
        onOk: () => {
          router.push({name: 'login'})
        }
      })
      break
    case 500:
      if (typeof error.response.data.code !== 'undefined') {
        return error.response.data
      }
      break
  }
})

export default axios

export function ajax(url = '', data = {}, method = 'GET', contentType = ReqContentType.APPLICATION_FORM) {
  return new Promise(function (resolve, reject) {
    let axiosRes
    switch (method) {
      case 'GET':
        let subffix = isEmptyObject(data) ? '' : '?' + jsonToFormData(data)
        axiosRes = axios.get(url + subffix)
        break
      case 'POST':
        axiosRes = axios({
          url: url,
          method: 'post',
          headers: {
            'Content-Type': contentType
          },
          data: contentType === ReqContentType.APPLICATION_FORM ? jsonToFormData(data) : JSON.stringify(data)
        })
        break
    }
    axiosRes.then(response => {
      resolve(response)
    }).catch(error => {
      reject(error);
    });
  });
}

/**
 * jsonP请求
 * @param url
 * @param data
 * @returns {Promise<any>}
 */
export function jsonpRequest(url = '', data = {}) {
  return new Promise(function (resolve, reject) {
    let subffix = isEmptyObject(data) ? '' : '?' + jsonToFormData(data)
    jsonp(url + subffix, null, (err, data) => {
      if (!err) {
        resolve(data)
      } else {
        reject(err);
      }
    })
  })
}


export {Method, BASE_URL, ReqContentType}
